/**
 * Created by GCX on 2017/5/18.
 */

$(function(){

    //实例化email推送
    $('.email-block-wrapper').emailBlock();

    // 默认只显示最新的一条版本信息
    $('.timeline-tr').each(function () {
        if($(this).index() == 0){
            $(this).find('.timeline-content').find('.box-info').css('display','block');
        }else{
            $(this).find('.timeline-content').find('.box-info').css('display','none');
            $(this).find('.timeline-content').find('.box-off-on').find('i').removeClass('icon-caret-down');
            $(this).find('.timeline-content').find('.box-off-on').find('i').addClass('icon-caret-right');
        }
    });

    //移除i标签的默认样式
    $('.box-off-on').find('.file-name').find('i').removeClass('icon-caret-right');

    // 加载formSelects
    layui.config({
        base: '/Public/layui-formSelects/dist/'
    }).extend({
        formSelects: 'formSelects-v4'
    });

    layui.use(['form','layer', 'formSelects'], function() {
        var layer = layui.layer,
            form = layui.form(),
            formSelects = layui.formSelects;

        var attachmentData = new Array();	//定义存放附件的对象

        var formData = null;

        $('#Modal-box').on('shown.bs.modal', function(e) {
            // 定义webuploader配置
            var webuploader_option = {
                auto: false,
                server: '/Software/upload',
                pick: {
                    id: '#picker',
                    multiple: false
                },
                fileVal: 'Filedata',
                accept: {
                    title: 'file',
                    extensions: 'zip,rar,jpg,png,jpeg,doc,xls,xlsx,docx,gif,pdf'
                },
                method: 'POST'
            };
            // 实例化webuploader
            window.uploader = WebUploader.create(webuploader_option);

            // 添加到队列时
            window.uploader.on('fileQueued', function (file) {
                var fileItem = ['<div class="file-item" id="' + file.id + '" style="width: 100%;">',
                    '<div class="pull-left">',
                    '<i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>',
                    '<div class="pull-right">',
                    '<i class="icon-remove" title="移除该文件"></i></div>',
                    '<div class="clearfix"></div>' + '</div>'].join('');
                $(webuploader_option.pick.id).next().append(fileItem);
            });

            // 上传之前
            window.uploader.on('uploadBeforeSend', function (block, data, headers) {
                data.SUB_NAME = $('#subName').val();
                data.PATH = '/Software/';
            });

            // 上传错误时
            window.uploader.on('error', function (code) {
                var msg = '';
                switch (code) {
                    case 'Q_EXCEED_NUM_LIMIT':
                        msg = '只能上传一个文件';
                        break;
                    case 'Q_EXCEED_SIZE_LIMIT':
                        msg = '文件大小超出限制';
                        break;
                    case 'Q_TYPE_DENIED':
                        msg = '文件格式不允许';
                        break;
                    case 'F_DUPLICATE':
                        msg = '文件已存在';
                        break;
                    default:
                        msg = code;
                }
                layer.msg(msg, {icon: 2, time: 2000});
            });

            window.uploader.on('fileDequeued', function(file){
                // console.log(window.uploader.getFiles());
            });

            // 上传成功时
            window.uploader.on('uploadSuccess', function (file, response) {
                if (response) {
                    attachmentData.push({
                        path: response.path,
                        savename: response.name,
                        ext: response.ext
                    });
                }
            });

            // 当所有文件上传结束时
            window.uploader.on('uploadFinished', function () {
                submitSoftware(formData);
            });


            // 删除队列文件
            $(document).on('click', '.uploader-file-queue .icon-remove', function () {
                var id = $(this).parent().parent().attr('id');
                // 删除队列中的文件
                window.uploader.removeFile(id, true);
                // 删除dom节点
                $(this).parent().parent().remove();
            });

        })

        // 提交
        form.on('submit(software)',function( data ){
            formData = data;
            // 如果队列里存在文件则上传
            if (window.uploader.getFiles().length) {
                // 上传成功后自动触发数据提交
                window.uploader.upload();
            } else {
                // 当软件类型为OA时可以不用上传附件
                if ($('#software-id').val() != 40) {
                    layer.alert('请上传附件');
                } else {
                    submitSoftware(formData)
                }
            }
            return false;
        })


        function submitSoftware(data) {
            data.field.attachment = JSON.stringify(attachmentData);
            var receiveList = {
                recipient: [],
                cc: []
            };
            if( $('.email-block-push').children().length ){
                $('.email-block-push .email-block-user-item-span').each(function (index) {
                    let tmpObj = new Object();
                    tmpObj.name = $(this).text();
                    tmpObj.id = $(this).attr('user-id');
                    tmpObj.email = $(this).attr('user-email');

                    receiveList.recipient.push(tmpObj);
                })
            }
            if( $('.email-block-cc').children().length ){
                $('.email-block-cc .email-block-user-item-span').each(function (index) {
                    let tmpObj = new Object();
                    tmpObj.name = $(this).text();
                    tmpObj.id = $(this).attr('user-id');
                    tmpObj.email = $(this).attr('user-email');
                    receiveList.cc.push(tmpObj);
                })
            }
            emailObj = JSON.stringify(receiveList);
            $.ajax({
                url : '/Software/addLog',
                type : 'POST',
                dataType : 'json',
                data : {
                    addRel : data.field,
                    email : emailObj,
                },
                beforeSend : function(){
                    layer.load(2, { shade : [0.5,'#fff'] });
                },
                success : function( response ){
                    if( response.flag > 0 ){
                        layer.closeAll();
                        layer.msg(response.msg, { icon : 1,time : 2000 });
                        setTimeout(function(){
                            location.reload();
                        },2000);
                    }else{
                        layer.closeAll();
                        layer.msg(response.msg, { icon : 2,time : 2000 });
                    }
                }
            });
            return false;
        }



    });


    // 销毁uploader
    $('#Modal-box').on('hide.bs.modal', function(e){
        window.uploader.destroy();
    });


    //里程碑

   $('.box-off-on a').click(function () {
       $(this).each(function () {
          if($(this).parent().next().css('display') == 'block'){
              $(this).find('.i-sty').removeClass('icon-caret-down');
              $(this).next().find('.file-name').find('i').removeClass('icon-caret-right');
              $(this).parent().next().css('display','none');
              $(this).find('.i-sty').addClass('icon-caret-right');
          }else {
              $(this).find('.i-sty').removeClass('icon-caret-right');
              $(this).next().find('.file-name').find('i').removeClass('icon-caret-right');
              $(this).parent().next().css('display','block');
              $(this).find('.i-sty').addClass('icon-caret-down');
          }
      })
    });


});